import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../demo/ui_demo.dart';
import 'dart:io';
import 'dart:convert';
import 'package:camera/camera.dart';
import '../local/model/app_model.dart';
import '../wonders/utils/utils.dart';
import  'package:permission_handler/permission_handler.dart';
class MyDemo extends StatelessWidget implements Demo {
  MyDemo(this.title);
  @override
  final String title;
  @override
  Widget build(BuildContext context) {
    return new HomePage(
      title: this.title,
    );
  }
}

class HomePage extends StatefulWidget {
  final String title;
  HomePage({this.title});
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  CameraController _controller;
  //获取相机
  List<CameraDescription> cameras;
  CameraDescription frontCamera;
  CameraDescription backCamera;
  String _imageInfo;
  String _imagePath;
  String _authInfo;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  void initState() {
    super.initState();
    //_imageInfo="图像信息";
    cameras=BaseModel.of<AppModel>(context).cameras;
    for(CameraDescription cameraDescription in cameras){
      if(cameraDescription.lensDirection==CameraLensDirection.back){
        backCamera=cameraDescription;
      }
      if(cameraDescription.lensDirection==CameraLensDirection.front){
        frontCamera=cameraDescription;
      }
    }
    _controller=CameraController(frontCamera==null?backCamera:frontCamera, ResolutionPreset.high);
    _controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }
  //拍照
  Future<String> _onCapture() async {
    if (!_controller.value.isInitialized) {
      showInSnackBar('Error: select a camera first.');
      return "no camera avalible";
    }
    String filePath;

/*  await requestPermission().then((_){

  });*/

    await PathUtils.instance.then((path) async {
      filePath = '${path.tempDirectory.path}/${timestamp()}.jpg';
      //filePath = '${path.documentsDirectory.path}/${timestamp()}.txt';
      // new File(filePath).writeAsStringSync("1123344");
      await _controller.takePicture(filePath);
      File file=File(filePath);
      file.readAsBytes().then((bytes){
        String base64str=base64Encode(bytes);
        print("bytes.length:${bytes.length}:${DateTime.now()}");
        //get accessToken
        getAuth().then((token){
          print("after getAuth:${DateTime.now()}");
          print("accessToken:$token");
          getFaceInfo(token,base64str).then((resp){
            print(resp);
            print("after getFace:${DateTime.now()}");
            Map face=resp.data;
            int age=face['result']['face_list'][0]['age'];
            String gender=face['result']['face_list'][0]['gender']['type'];
            print('age:$age');
            print('gender:$gender');
            setState(() {
              _imagePath=filePath;
              _imageInfo='''gender:$gender age:$age''';
            });
          });
        }
        );
        //HttpUtils().post(path)
      });
    });

    return filePath;
  }
  //切换镜头
  _onCameraRoll() async{
    CameraLensDirection _now=_controller.description.lensDirection;
    if (_controller != null) {
      await _controller.dispose();
    }
    if(_now==CameraLensDirection.back){
      _controller=CameraController(frontCamera, ResolutionPreset.low);
    }else{
      _controller=CameraController(backCamera, ResolutionPreset.low);
    }
    // If the controller is updated then update the UI.
    _controller.addListener(() {
      if (mounted) setState(() {});
      if (_controller.value.hasError) {
        print('Camera error ${_controller.value.errorDescription}');
      }
    });

    try {
      await _controller.initialize();
    } on CameraException catch (e) {
      print(e);
    }

    if (mounted) {
      setState(() {});
    }
  }
  @override
  Widget build(BuildContext context) {

    if(_controller==null||!_controller.value.isInitialized) return Text("未找到相机");
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(title: Text(widget.title),),
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 4,
            child: Container(
              child:Center(
                child: AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: CameraPreview(_controller),
                ),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    FlatButton(onPressed: _onCameraRoll, child: Icon(Icons.camera_roll)),
                    FlatButton(onPressed: _onCapture, child: Icon(Icons.add_a_photo)),

                  ],
                )
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
                child: _imagePath!=null?Image.file(File(_imagePath)):null
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
                child: Text(
                  _imageInfo!=null?_imageInfo:"",
                )
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
  void _showCameraException(CameraException e) {
    print(e.code+":"+e.description);
    showInSnackBar('Error: ${e.code}\n${e.description}');
  }
  void showInSnackBar(String message) {
    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
  }
  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();
  Future requestPermission() async {
    // 申请权限
    Map<PermissionGroup, PermissionStatus> permissions =
    await PermissionHandler().requestPermissions([PermissionGroup.storage,PermissionGroup.camera]);
    // 申请结果
    PermissionStatus permission =
    await PermissionHandler().checkPermissionStatus(PermissionGroup.storage,);
    if (permission == PermissionStatus.granted) {
      showInSnackBar( "存储权限申请通过");
    } else {
      showInSnackBar( "存储权限申请被拒绝");
    }
    // 申请结果
    permission =
    await PermissionHandler().checkPermissionStatus(PermissionGroup.camera,);
    if (permission == PermissionStatus.granted) {
      showInSnackBar( "相机权限申请通过");
    } else {
      showInSnackBar( "相机权限申请被拒绝");
    }

  }

  //获取access_token
  Future<String> getAuth() async{
    if(_authInfo!=null) return Future.value(_authInfo);
    String ak='ozt0wf9Un27lGz5XdSXzQpdk';
    String sk='oGMj53TgeI0t68hIAw5cOHq0CzgUPS1E';
    // 获取token地址
    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
    String getAccessTokenUrl = authHost
        // 1. grant_type为固定参数
        + "grant_type=client_credentials"
        // 2. 官网获取的 API Key
        + "&client_id=" + ak
        // 3. 官网获取的 Secret Key
        + "&client_secret=" + sk;

    BaseResp resp= await HttpUtils().post(getAccessTokenUrl);
    _authInfo=resp.data['access_token'];
    return resp.data['access_token'];

  }
  //人脸识别
  Future<BaseResp> getFaceInfo(String accessToken,String base64Str) async{
    String url='https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=$accessToken';
    Map data={'image':base64Str,'image_type':'BASE64','face_field':'age,gender'};
    Options options=Options();
    options.contentType=ContentType.json;
     return await HttpUtils().post(url,
     data: data,
     options: options
     );
  }
}

